package com.yang.SpringTest.utils.beanFactoryUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.beans.factory.BeanFactoryUtils;

import java.util.Arrays;
import java.util.Map;

/**
 * <p>BeanFactoryUtils学习 </p>
 *
 * @author By: chengxuyuanshitang <br>
 * @Package: com.yang.SpringTest.utils.beanFactoryUtils <br>
 * @CreateTime: 2024-11-20 14:42 <br>
 */
@Slf4j
public class BeanFactoryUtilsTest {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(BeanFactoryUtilsAppConfig.class);
        ListableBeanFactory beanFactory = (ListableBeanFactory) context;
        log.info("**************** IOC容器启动完成....");
        // 获取所有 DemoService 类型的 Bean 名称
        String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, DemoService.class);
        for (String beanName : beanNames) {
            System.out.println("-------Bean name is : " + beanName);
        }

        // 获取所有 DemoService 类型的 Bean 实例
        Map<String, DemoService> beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(beanFactory, DemoService.class);
        for (Map.Entry<String, DemoService> entry : beansOfType.entrySet()) {
            System.out.println("============Bean name is : " + entry.getKey());
            entry.getValue().doSomething();
        }
        // 获取当前 BeanFactory 及其父 BeanFactory 中所有 Bean 的名称列表
        String[] definitionList= BeanFactoryUtils.beanNamesIncludingAncestors(beanFactory);
        Arrays.stream(definitionList).forEach((definitionName) -> System.out.println("****************  Bean name is " + definitionName));
        // 获取 Bean 的总数量
        int beanCount = BeanFactoryUtils.countBeansIncludingAncestors(beanFactory);
        System.out.println("Total bean count is: " + beanCount);


    }
}